package com.liuqi.voicenotes.reminder

import android.content.Context
import android.speech.tts.TextToSpeech
import android.util.Log
import java.util.Locale

object SpeechUtils {
    private lateinit var tts: TextToSpeech
    fun speakNow(context: Context, text: String) {
        Log.d(TAG, "speakNow: '$text'")
        tts = TextToSpeech(context) { status ->
            Log.d(TAG, "tts init status=$status")
            if (status == TextToSpeech.SUCCESS) {
                try {
                    // 简化：直接设置中文；若系统默认非中文也能正常播报
                    tts.language = Locale.CHINESE
                } catch (e: Exception) {
                    Log.w(TAG, "setLanguage error: ${e.message}")
                }
                try {
                    // 简化：直接 speak，不设置额外属性或音频焦点
                    tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, "vn_${System.currentTimeMillis()}")
                } catch (e: Exception) {
                    Log.e(TAG, "tts.speak error: ${e.message}", e)
                }
            } else {
                Log.e(TAG, "tts init failed: $status")
            }
        }

        // 可选：监听并在完成后释放资源，避免长期占用
        tts.setOnUtteranceProgressListener(object : android.speech.tts.UtteranceProgressListener() {
            override fun onStart(utteranceId: String?) {
                Log.d(TAG, "onStart id=$utteranceId")
            }
            override fun onDone(utteranceId: String?) {
                Log.d(TAG, "onDone id=$utteranceId")
                try { tts.shutdown() } catch (_: Exception) {}
            }
            override fun onError(utteranceId: String?) {
                Log.e(TAG, "onError id=$utteranceId")
                try { tts.shutdown() } catch (_: Exception) {}
            }
        })
    }

    private const val TAG = "SpeechUtils"
}